﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Collections;
using Microsoft.VisualBasic.FileIO;
using System.Net.Mail;
using System.Drawing.Printing;

namespace SoundServant
{
    public class StoredRecording
    {
        public readonly int Id;
        string title;
        bool current = false;
        MeetingType type;
        DirectoryInfo directory;
        DateTime date;
        ArrayList discs = new ArrayList();
        public StoredDisc CurrentDisc = null;
        int locks = 0;
        Congregation congregation;
        FileInfo mp3File = null;
        private Recorder recorder;
        internal int numOfTracks = 0;

        public DirectoryInfo Directory { get { return directory; } }
        public bool Current { get { return current; } }
        public ArrayList Discs { get { return discs; } }
        public string FormatedType { get { return SS.FullMeetingType(type); } }
        public DateTime Date { get { return date; } }
        public string FormatedDate { get { return date.ToString("ddd dd MMM yy HH:MM"); } }
        public string AbbrvDateType { get { return date.ToString("dd.MM.yy") + " | " + SS.AbbrMeetingType(type); } }
        public int Locks { get { return locks; } set { locks = value; } }
        public FileInfo Mp3File { get { return mp3File; } }
        public Congregation Congregation { get { return congregation; } }
        public Recorder Recorder { get { return recorder; } }
        public TimeSpan Length
        {
            get
            {
                if (!current)
                {
                    TimeSpan length = new TimeSpan(0);
                    foreach (StoredDisc disc in discs) { length += disc.Length; }
                    return length;
                }
                else
                {
                    return Recorder.RecorderTimePassed;
                }
            }
        }
        public int NumOfTracks
        {
            get { return numOfTracks; }
        }
        public string Title
        {
            get { return title; }
            set
            {
                SqlConnection connection = SS.Connection();

                title = value;
                SqlCommand dbCommand = new SqlCommand("UPDATE recordings SET recTitle = '" + SS.MakeSQLSafe(title) + "' WHERE recId = " + Id, connection);
                dbCommand.ExecuteNonQuery();
                connection.Close();
                connection.Dispose();
            }
        }
        public MeetingType Type
        {
            get { return type; }
            set
            {
                SqlConnection connection = SS.Connection();
                type = value;
                SqlCommand dbCommand = new SqlCommand("UPDATE recordings SET recType = " + (int)type + " WHERE recId = " + Id, connection);
                dbCommand.ExecuteNonQuery();
                connection.Close();
                connection.Dispose();
            }
        }

        public delegate void VoidEventHandler();
        public event VoidEventHandler Finished;
        public event VoidEventHandler Deleted;
        public event VoidEventHandler Updated;
        public delegate void NewDiscCreatedEventHandler();
        public event NewDiscCreatedEventHandler NewDiscCreated;
        public delegate void NewTrackCreatedEventHandler();
        public event NewTrackCreatedEventHandler NewTrackCreated;

        static public bool Delete(int id)
        {
            return false;
        }

        public StoredRecording(MeetingType t, Congregation c, Recorder j)
        {
            SqlConnection connection = SS.Connection();
            congregation = c;
            recorder = j;
            SqlCommand dbCommand = new SqlCommand("INSERT INTO recordings (recDate, recType, recCong) VALUES (CURRENT_TIMESTAMP, " + (int)t + ", " + congregation.Id + ") SELECT CAST(scope_identity() AS int)", connection);
            Id = (int)dbCommand.ExecuteScalar();
            connection.Close();
            connection.Dispose();
            current = true;
            type = t;
            title = "";
            locks++;
            date = DateTime.Now;
            directory = new DirectoryInfo(Options.Default.BaseDirectory + "\\" + Options.Default.RecordDirectory + "\\" + Id);
            directory.Create();
            mp3File = new FileInfo(directory.FullName + "\\" + "mp3.mp3");
        }

        internal void NewTrackCreatedProxy()
        {
            if (NewTrackCreated != null) NewTrackCreated();
        }

        public StoredRecording(int i)
        {
            Id = i;

            SqlCommand dbCommand;
            SqlDataReader dbReader;
            SqlConnection connection = SS.Connection();

            dbCommand = new SqlCommand("SELECT * FROM recordings WHERE recId = " + Id, connection);
            dbReader = dbCommand.ExecuteReader();
            dbReader.Read();
            type = (MeetingType)dbReader["recType"];
            date = DateTime.Parse(dbReader["recDate"].ToString());
            directory = new DirectoryInfo(Options.Default.BaseDirectory + "\\" + Options.Default.RecordDirectory + "\\" + Id);
            title = dbReader["recTitle"].ToString();
            congregation = new Congregation((int)dbReader["recCong"]);
            mp3File = new FileInfo(directory.FullName + "\\" + "mp3.mp3");

            dbReader.Close();

            dbCommand = new SqlCommand("SELECT discID FROM discs WHERE discRec = " + Id, connection);
            dbReader = dbCommand.ExecuteReader();

            if (dbReader.HasRows) while (dbReader.Read())
                {
                    StoredDisc discToAdd = new StoredDisc(this, (int)dbReader[0]);
                    discs.Add(discToAdd);
                }

            dbReader.Close();
            connection.Close();
            connection.Dispose();
        }

        public int CreateNewDisc(string t)
        {
            int newDiscId;
            discs.Add(new StoredDisc(this, t, out newDiscId));
            if (NewDiscCreated != null) NewDiscCreated();
            return newDiscId;
        }

        public void Finish()
        {
            if (current)
            {
                current = false;
                CurrentDisc.Finish();
                CurrentDisc = null;

                if (Finished != null) Finished();
            }
        }

        public void ExportMp3(string to)
        {
            if (mp3File != null & !current)
            {
                string copyTo = to + congregation.Name + " - " + SS.FullMeetingType(type) + " - " + date.ToString("MM.dd.yy") + ".mp3";
                Logs.Information("Recording", "Exporting recording as MP3 - Recording Id: " + Id + " From: " + mp3File.FullName + " Size: " + (mp3File.Length / (long)1048576).ToString("00.00") + "mb To: " + copyTo);
                FileSystem.CopyFile(mp3File.FullName, copyTo, UIOption.AllDialogs, UICancelOption.DoNothing);
            }
        }

        public void Delete()
        {
            if (!current)
            {
                foreach (StoredDisc disc in discs)
                {
                    disc.Delete();
                }

                directory.Delete(true);
                SqlConnection connection = SS.Connection();
                SqlCommand dbCommand = new SqlCommand("DELETE FROM recordings WHERE recId = " + Id, connection);
                dbCommand.ExecuteNonQuery();

                connection.Close();
                connection.Dispose();
                if (Deleted != null) Deleted();
            }
        }
    }
}
